# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  station.py
#       Author @  Huoty
#  Create date @  2016-07-23 15:01:21
#  Description @  Get all the station code and translate
#                 station to code
# *************************************************************

from __future__ import absolute_import

import os
import re
try:
    import cPickle as pickle
except ImportError:
    import pickle

from .utils import request_resources


uri_12306 = "https://kyfw.12306.cn"
ticket_query_page = uri_12306 + "/otn/lcxxcx/init"
_pattern_js = r'<script .*src="(.*%s.*)" .*></script>'

station_name_data_file = "/tmp/tronitor_station_name.db"
station_open_data_file = "/tmp/tronitor_station_open.db"

def fetch_js_url(js_name):
    body = request_resources(ticket_query_page)
    if '.' in js_name:
        js_name = "\\.".join(js_name.split('.'))
    pattern_station_name = _pattern_js % js_name
    match = re.search(pattern_station_name, body)
    ret = match.groups()
    if len(ret) != 1:
        raise Exception("Request to the content is wrong!")
    return uri_12306 + ret[0]

def update_station_name_data():
    """update station name data"""
    station_name_js = fetch_js_url("station_name.js")
    body = request_resources(station_name_js)
    stations = re.findall(u'([\u4e00-\u9fa5]+)\|([A-Z]+)', body)

    if os.path.exists(station_name_data_file):
        os.remove(station_name_data_file)

    with open(station_name_data_file, 'wb') as f:
        pickle.dump(dict(stations), f, pickle.HIGHEST_PROTOCOL)

def update_station_open_data():
    """update station open data"""
    station_open_js = fetch_js_url("qss.js")
    body = request_resources(station_open_js)
    stations = re.findall(u'"([\u4e00-\u9fa5]+)":"([0-9:]+)"', body)

    if os.path.exists(station_open_data_file):
        os.remove(station_open_data_file)

    with open(station_open_data_file, 'wb') as f:
        pickle.dump(dict(stations), f, pickle.HIGHEST_PROTOCOL)

def station_to_code(station):
    if not os.path.exists(station_name_data_file):
        update_station_name_data()

    with open(station_name_data_file, 'rb') as f:
        try:
            stations = pickle.load(f)
        except ValueError:
            # Compatible with python 2 and 3
            update_station_name_data()
            with open(station_name_data_file, 'rb') as f:
                stations = pickle.load(f)
            pass

    return stations.get(station, None)

def get_station_open_time(station):
    if not os.path.exists(station_open_data_file):
        update_station_open_data()

    with open(station_open_data_file, 'rb') as f:
        try:
            stations = pickle.load(f)
        except ValueError:
            # Compatible with python 2 and 3
            update_station_open_data()
            with open(station_open_data_file, 'rb') as f:
                stations = pickle.load(f)
            pass

    return stations.get(station, None)
